package org.hcf.utils.word;
import java.io.*;
import java.util.Iterator;
import java.util.Map;

/**
 * 动态更改word文档（mht）
 * 注意：$keys$ 不能过长
 */
public class ReportToWord {
	

	/**
	 * 替换动态文档
	 * 
	 * @param content
	 * @param markersign
	 * @param replacecontent
	 * @return
	 */
	public String replaceStr(String content, String markersign,String replacecontent) {
		String rc = encode2HtmlUnicode(replacecontent);
		String target = "";
		markersign = "\\$" + markersign + "\\$";
		target = content.replaceAll(markersign, rc);
		return target;
	}

	/**
	 * 把给定的str转换为10进制表示的unicode 目前只是用于mht模板的转码
	 *
	 * @param str
	 * @return
	 */
	public String encode2HtmlUnicode(String str) {
		if (str == null)
			return "";
		StringBuffer sb = new StringBuffer(str.length() * 2);
		for (int i = 0; i < str.length(); i++) {
			sb.append(encode2HtmlUnicode(str.charAt(i)));
		}
		return sb.toString();
	}

	public String encode2HtmlUnicode(char character) {
		if (character > 255) {
			return "&#" + (character & 0xffff) + ";";
		} else {
			return String.valueOf(character);
		}
	}

	/**
	 * 读取和输出文件
	 * 
	 * @param inputPath 输入
	 * @param outPath 输出
	 * @param data 替换的内容 key-val
	 */
	public void rgModel(String inputPath, String outPath, Map data) {
		/* 字节形式读取模板文件内容,将结果转为字符串 */
		String sourname = inputPath;
		String sourcecontent = "";
		InputStream ins = null;
		try {
			ins = new FileInputStream(sourname);
			byte[] b = new byte[16384000];// 提高对文件的读取速度，特别是对于1M以上的文件
			if (ins == null) {
				// 源模板文件不存在
//				logger.debug("源模板文件不存在");
				throw new Exception("Source template file does not exist");
			}
			int bytesRead = 0;
			while (true) {
				bytesRead = ins.read(b, 0, 16384000);
				if (bytesRead == -1) {
					// 读取模板文件结束
					break;
				}
				sourcecontent += new String(b, 0, bytesRead);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		/* 修改变化部分 */
		String targetcontent = "";
		String oldText = "";
		Object newValue;
		/* 结果输出保存到文件 */
		try {
			Iterator keys = data.keySet().iterator();
			int keysfirst = 0;
			while (keys.hasNext()) {
				oldText = (String) keys.next();
				newValue = data.get(oldText);
				String newText = (String) newValue;
				if (keysfirst == 0) {
					targetcontent = replaceStr(sourcecontent, oldText, newText);
					keysfirst = 1;
				} else {
					targetcontent = replaceStr(targetcontent, oldText, newText);
					keysfirst = 1;
				}
			}
			File file = new File(outPath);
			if (file.exists()) {
				file.delete();
			}
			FileWriter fw = new FileWriter(outPath, true);
			PrintWriter out = new PrintWriter(fw);
			if (targetcontent.equals("") || targetcontent == "") {
				out.println(sourcecontent);
			} else {
				out.println(targetcontent);
			}
			out.close();
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
